package com.example.hcd.functionactivity;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.hcd.R;
import com.example.hcd.datamanage.PeopleNextData;
import com.example.hcd.datamanage.SealuseData;
import com.example.hcd.datamanage.UserInfo;
import com.example.hcd.internet.InternetKeep;
import com.example.hcd.internet.LinkHelp;
import com.example.hcd.internet.URLS;
import com.example.hcd.tool.CommonDialog;
import com.example.hcd.tool.MyLoadingDialog;
import com.example.hcd.tool.ToastHelp;
import com.wheel.StrericWheelAdapter;
import com.wheel.WheelView;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.animation.AnticipateOvershootInterpolator;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class SealuseApply extends BaseActivity implements OnClickListener{
	private LayoutInflater inflater;
	private SealuseApply context;
	private View main_view;
	private SealuseData sealuseData;


	private CommonDialog popipwindow,popipwindow1;
	

	
	private TextView xiaedit1;
	private TextView xiaedit2;
	
	private TextView timeedit;
	
	//滚动时间
	private WheelView yearWheel,monthWheel,dayWheel,hourWheel,minuteWheel;
	public static String[] yearContent=null;
	public static String[] monthContent=null;
	public static String[] dayContent=null;
	public static String[] hourContent = null;
	public static String[] minuteContent=null;
	
	//获取下一步处理人
	private ArrayList<PeopleNextData> peoples_next;
			private TextView nextPeople;
			
			private RelativeLayout nextPeopleBg;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		mPageName = "SealuseApply";
		inflater = LayoutInflater.from(this);
		context = this;
		main_view = inflater.inflate(R.layout.sealuse_apply_view, null);
		setContentView(main_view);
		
		initview();
	}
	
	private void initview()
	{
		//初始化时间滚动
		initContent();
		//借款申請人
		EditText applyEdit = (EditText) findViewById(R.id.editText);
		applyEdit.setText(UserInfo.getUserInfor().getName());
		
		applyEdit = (EditText) findViewById(R.id.editText1);
		applyEdit.setText(UserInfo.getUserInfor().getDepartmnet());
		
		sealuseData = new SealuseData(null);
		// 返回键
		ImageView backBtn = (ImageView) findViewById(R.id.title_bar_btn_left);
		// 提交键
		ImageView uploadBtn = (ImageView) findViewById(R.id.title_bar_btn_right);
		backBtn.setOnClickListener(context);
		uploadBtn.setOnClickListener(context);
		
		xiaedit1 = (TextView)main_view.findViewById(R.id.title21);
		xiaedit1.setOnClickListener(this);
		xiaedit2 = (TextView)main_view.findViewById(R.id.title31);
		xiaedit2.setOnClickListener(this);
		
		findViewById(R.id.btn_image1).setOnClickListener(context);
		findViewById(R.id.btn_image2).setOnClickListener(context);
		findViewById(R.id.btn_image3).setOnClickListener(context);
		
	
		timeedit = (TextView)main_view.findViewById(R.id.title41);
		timeedit.setOnClickListener(this);
		if (InternetKeep.getInstence().isSystemInfoLoad) {
			
			popipwindow = new CommonDialog(this);

			for (int i = 0; i < InternetKeep.getInstence().getSealInfolist().size(); i++)
			{
				final View item = (View) LayoutInflater.from(context).inflate(R.layout.common_dialog_item, null);

				final TextView text = (TextView) item.findViewById(R.id.item_text);
				text.setText(InternetKeep.getInstence().getSealInfolist().get(i).sealName);
				popipwindow.addView(item);
				xiaedit1.setText(InternetKeep.getInstence().getSealInfolist().get(0).sealName);
				text.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0)
					{
						xiaedit1.setText(text.getText().toString());
						popipwindow.dismiss();
					}
				});
			}
			
			String[] texts = new String[] { "是", "否" };
			popipwindow1 = new CommonDialog(this);
			for (int i = 0; i < texts.length; i++)
			{
				final View item = (View) inflater.inflate(R.layout.common_dialog_item, null);

				final TextView text = (TextView) item.findViewById(R.id.item_text);
				text.setText(texts[i]);
				popipwindow1.addView(item);
				xiaedit2.setText(texts[0]);
				isTimeShowOrHide();
				text.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0)
					{
						xiaedit2.setText(text.getText().toString());
						isTimeShowOrHide();
						popipwindow1.dismiss();
						//获取下一步处理人
						getNextPeople next = new getNextPeople();
						next.execute();
					}
				});

			}
			
			
		} else {
			//Toast.makeText(context, "报销项目加载失败", Toast.LENGTH_SHORT).show();
			ToastHelp.doToast(context,  "用章列表加载失败");
			finish();
		}
		
		
	
		
		isTimeShowOrHide();
		//获取下一步处理人
		nextPeopleBg = (RelativeLayout)main_view.findViewById(R.id.next_people_bg);
				nextPeople = (TextView)main_view.findViewById(R.id.next_people);
				peoples_next = new ArrayList<PeopleNextData>();
				//获取下一步处理人
				getNextPeople next = new getNextPeople();
				next.execute();
				
			}
			//获取下一步处理人
				private class getNextPeople extends AsyncTask<String, Integer, String> {

					// private ProgressDialog mProgress;
					public getNextPeople() {
					}

					@Override
					protected void onPreExecute() {
						super.onPreExecute();
					}

					@Override
					protected String doInBackground(String... params) {
						String result = null;
						HttpResponse response = null;
						BufferedReader reader = null;
						try {
							ArrayList<NameValuePair> vs = new ArrayList<NameValuePair>();
							vs.add(new BasicNameValuePair("taskId",""));
							vs.add(new BasicNameValuePair("fp_Lending", xiaedit2.getText().equals("否")?"false":"true"));
							response = LinkHelp.post(URLS.getNextWorkUser("sealApp"), vs, false);

							if (response != null) {
								StatusLine line = response.getStatusLine();
								if (line.getStatusCode() == 200) {
									reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
									StringBuilder sb = new StringBuilder();
									for (String s = reader.readLine(); s != null; s = reader.readLine()) {
										sb.append(s);
									}
									reader.close();
									result = sb.toString();
									
									System.out.println(result);
								}
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
						return result;
					}

					@Override
					protected void onPostExecute(String result) {
						
						if(result==null)
						{
							ToastHelp.doToast(context, "网络异常！");
							return;
						}
						
						JSONObject jsonObject;
			            try {
			                jsonObject = new JSONObject(result);
			                if (jsonObject.isNull("code")) {
			                    String status = jsonObject.getString("status");
			                    if (status.equals("success")) {
									{
										peoples_next.clear();
										if (result.contains("workUserInfo")) {
											JSONArray peoples = jsonObject.getJSONArray("workUserInfo");
											for (int i = 0; i < peoples.length(); i++) {
												PeopleNextData data = new PeopleNextData();
												JSONObject myJS = peoples.getJSONObject(i);
												data.setUserId(myJS.getString("userId"));
												data.setUserName(myJS.getString("userName"));
												data.setDepartmentId(myJS.getString("departmentId"));
												data.setDepartmentName(myJS.getString("departmentName"));
												data.setCompanyId(myJS.getString("companyId"));
												data.setCompanyName(myJS.getString("companyName"));
												data.setIsHead(myJS.getString("isHead"));
												data.setCode(myJS.getString("code"));
												peoples_next.add(data);
											}
											if (peoples_next.size() >= 1) {
												nextPeople.setText(peoples_next.get(0).getUserName() + "("
														+ peoples_next.get(0).getDepartmentName() + ")");
											}else
											{
												nextPeopleBg.setVisibility(View.GONE);
											}

										} else if (result.contains("noNeedWorkUserId")) {
											if (jsonObject.getString("noNeedWorkUserId").equals("true")) {
												nextPeople.setText("下一步不需要处理人");
												nextPeopleBg.setVisibility(View.GONE);
											}

										} else if (result.contains("msg")) {
											nextPeople.setText(jsonObject.getString("msg"));
											
											if(jsonObject.getString("msg").contains("不需要"))
			                    			{
			                    				nextPeopleBg.setVisibility(View.GONE);
			                    			}
											
										} else {
											System.out.println("Shit!服务器给的什么破数据");
										}

									}

								} else {
									String msg = jsonObject.getString("msg");
									//Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
									ToastHelp.doToastInTop(context, msg);
									nextPeople.setText("空");
									nextPeopleBg.setVisibility(View.GONE);
								}
			                    
			                }}  
			            catch (JSONException e) {
			                e.printStackTrace();
			            }
					}

				}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		int id = arg0.getId();
		// //隐藏软键盘
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(main_view.getWindowToken(), 0);

		getCurrentFocus().clearFocus();
		EditText edit = (EditText)main_view.findViewById(R.id.edit_focuse_unable);
		edit.setFocusable(true);
		edit.requestFocus();
		
		switch (id) {
		case R.id.title_bar_btn_left:
			finish();
			break;

		case R.id.title_bar_btn_right:
			upload();
			break;
		case R.id.btn_image1:	
		case R.id.title21: {
			Window window = popipwindow.getWindow();
			window.setGravity(Gravity.BOTTOM);
			window.setWindowAnimations(R.style.pop_float_win_anim_style);
			popipwindow.show();
		}
			break;
		case R.id.btn_image2:	
		case R.id.title31: {
			Window window = popipwindow1.getWindow();
			window.setGravity(Gravity.BOTTOM);
			window.setWindowAnimations(R.style.pop_float_win_anim_style);
			popipwindow1.show();
		}
			break;
		case R.id.btn_image3:
		case R.id.title41: 
		{
			View view = ((LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE)).inflate(R.layout.time_picker, null); 
			
    		Calendar calendar = Calendar.getInstance();
    	    int curYear = calendar.get(Calendar.YEAR);
            int curMonth= calendar.get(Calendar.MONTH)+1;
            int curDay = calendar.get(Calendar.DAY_OF_MONTH);
            int curHour = calendar.get(Calendar.HOUR_OF_DAY);
            int curMinute = calendar.get(Calendar.MINUTE);
     	    
    	    yearWheel = (WheelView)view.findViewById(R.id.yearwheel);
    	    monthWheel = (WheelView)view.findViewById(R.id.monthwheel);
    	    dayWheel = (WheelView)view.findViewById(R.id.daywheel);
    	    hourWheel = (WheelView)view.findViewById(R.id.hourwheel);
    	    minuteWheel = (WheelView)view.findViewById(R.id.minutewheel);
  	   
            AlertDialog.Builder builder = new AlertDialog.Builder(this);  
            builder.setView(view); 
            
            yearWheel.setAdapter(new StrericWheelAdapter(yearContent));
		 	yearWheel.setCurrentItem(curYear-2013);
		    yearWheel.setCyclic(true);
		    yearWheel.setInterpolator(new AnticipateOvershootInterpolator());
	        
	 
	        monthWheel.setAdapter(new StrericWheelAdapter(monthContent));
	       
	        monthWheel.setCurrentItem(curMonth-1);
	     
	        monthWheel.setCyclic(true);
	        monthWheel.setInterpolator(new AnticipateOvershootInterpolator());
	        
	        dayWheel.setAdapter(new StrericWheelAdapter(dayContent));
	        dayWheel.setCurrentItem(curDay-1);
	        dayWheel.setCyclic(true);
	        dayWheel.setInterpolator(new AnticipateOvershootInterpolator());
	        
	        hourWheel.setAdapter(new StrericWheelAdapter(hourContent));
	        hourWheel.setCurrentItem(curHour);
	        hourWheel.setCyclic(true);
	        hourWheel.setInterpolator(new AnticipateOvershootInterpolator());
	        
	        minuteWheel.setAdapter(new StrericWheelAdapter(minuteContent));
	        minuteWheel.setCurrentItem(curMinute);
	        minuteWheel.setCyclic(true);
	        minuteWheel.setInterpolator(new AnticipateOvershootInterpolator());

	        builder.setTitle("选取时间");  
	        builder.setPositiveButton("确  定", new DialogInterface.OnClickListener() {  

	        	@Override  
            	public void onClick(DialogInterface dialog, int which) {  
            	
	        		StringBuffer sb = new StringBuffer();  
	        		sb.append(yearWheel.getCurrentItemValue()).append("-")
	        		.append(monthWheel.getCurrentItemValue()).append("-")
	        		.append(dayWheel.getCurrentItemValue());
     
	        		sb.append(" ");  
	        		sb.append(hourWheel.getCurrentItemValue())  
	        		.append(":").append(minuteWheel.getCurrentItemValue())
	        		;  
	        		timeedit.setText(sb);
	        		dialog.cancel();  
            	}  
	        });  
       
	        builder.show();
			
		}
			break;
		default:
			break;
		}
	}
	
	private boolean isTimeShowOrHide()
	{
		if(xiaedit2.getText().equals("是"))
		{
			RelativeLayout timeadd = (RelativeLayout)main_view.findViewById(R.id.timeadd);
			timeadd.setVisibility(View.VISIBLE);
			return true;
		}else
		{
			RelativeLayout timeadd = (RelativeLayout)main_view.findViewById(R.id.timeadd);
			timeadd.setVisibility(View.GONE);
			return false;
		}
		
		
		
	}
	
	public void initContent()
	{
		yearContent = new String[10];
		for(int i=0;i<10;i++)
			yearContent[i] = String.valueOf(i+2013);
		
		monthContent = new String[12];
		for(int i=0;i<12;i++)
		{
			monthContent[i]= String.valueOf(i+1);
			if(monthContent[i].length()<2)
	        {
				monthContent[i] = "0"+monthContent[i];
	        }
		}
			
		dayContent = new String[31];
		for(int i=0;i<31;i++)
		{
			dayContent[i]=String.valueOf(i+1);
			if(dayContent[i].length()<2)
	        {
				dayContent[i] = "0"+dayContent[i];
	        }
		}	
		hourContent = new String[24];
		for(int i=0;i<24;i++)
		{
			hourContent[i]= String.valueOf(i);
			if(hourContent[i].length()<2)
	        {
				hourContent[i] = "0"+hourContent[i];
	        }
		}
			
		minuteContent = new String[60];
		for(int i=0;i<60;i++)
		{
			minuteContent[i]=String.valueOf(i);
			if(minuteContent[i].length()<2)
	        {
				minuteContent[i] = "0"+minuteContent[i];
	        }
		}
	}
	
	private void upload()
	{
		if(isCanUpload())
		{
			UpdateLoadInfo upload = new UpdateLoadInfo(sealuseData);
			upload.execute();
		}
	}
	
	/*
	 * 传送数据到服务器
	 */
	private class UpdateLoadInfo extends AsyncTask<String, Integer, String> {
		SealuseData sealuseData;
		
		private MyLoadingDialog dialog;

		// private ProgressDialog mProgress;
		public UpdateLoadInfo(SealuseData sealuseData) {

			this.sealuseData = sealuseData;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog = new MyLoadingDialog(context, null, "提交中...", false);
		}

		@Override
		protected String doInBackground(String... params) {
			String result = null;
			HttpResponse response = null;
			BufferedReader reader = null;
			try {
				
				ArrayList<NameValuePair> vs = new ArrayList<NameValuePair>();
				
				vs.add(new BasicNameValuePair("sealType",sealuseData.getSealName()));
				vs.add(new BasicNameValuePair("fp_Lending", sealuseData.getIsLendingout()));
				if(isTimeShowOrHide())
				{
					vs.add(new BasicNameValuePair("estimereturn_long", ""+sealuseData.getEstimereturn(false)));
				}
				EditText edit = (EditText)main_view.findViewById(R.id.editText5);
				vs.add(new BasicNameValuePair("remark", edit.getText().toString()==null?"":edit.getText().toString()));
				
				
				response = LinkHelp.post(URLS.getSealStart(), vs, false);

				if (response != null) {
					StatusLine line = response.getStatusLine();
					if (line.getStatusCode() == 200) {
						reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
						StringBuilder sb = new StringBuilder();
						for (String s = reader.readLine(); s != null; s = reader.readLine()) {
							sb.append(s);
						}
						reader.close();
						result = sb.toString();
						
						System.out.println(result);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return result;
		}

		@Override
		protected void onPostExecute(String result) {
			dialog.dimiss();
			JSONObject jsonObject;
            try {
                jsonObject = new JSONObject(result);
                if (jsonObject.isNull("code")) {
                    String status = jsonObject.getString("status");
                    UserInfo info = UserInfo.getUserInfor();
                    if (status.equals("success")) {
                        Toast.makeText(context, "提交成功", Toast.LENGTH_SHORT).show();

                        	finish();
                    } else {
                    	String msg = jsonObject.getString("msg");
                    	//Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
                    	ToastHelp.doToast(context, msg);
                    }
                    
                }}  
            catch (JSONException e) {
                e.printStackTrace();
            }
		}

	}
	
	public boolean isCanUpload()  {

		if (xiaedit1.getText().toString().equals("请选择印章")) {
			//Toast.makeText(context, "请选择印章", Toast.LENGTH_SHORT).show();
			ToastHelp.doToast(context,  "请选择印章");
			return false;
		} else {
			sealuseData.setSealName((xiaedit1.getText().toString()));
		}
		if (xiaedit2.getText().toString().equals("是否外借")) {
			//Toast.makeText(context, "请选择是否外借", Toast.LENGTH_SHORT).show();
			ToastHelp.doToast(context,  "请选择是否外借");
			return false;
		} else {
			sealuseData.setIsLendingout(xiaedit2.getText().equals("否")?"false":"true");
		}
		
		if(xiaedit2.getText().equals("是"))
		{
			if(timeedit.getText().equals("预计归还时间"))
			{
				//Toast.makeText(context, "请选择归还时间", Toast.LENGTH_SHORT).show();
				ToastHelp.doToast(context,  "请选择归还时间");
				return false;
			}else
			{
				try {
					SimpleDateFormat mFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm");
					//继续转换得到秒数的long型  
					Date time = mFormat.parse(timeedit.getText().toString());
					
					long dtime = time.getTime();
					sealuseData.setEstimereturn(""+dtime);
					
				} catch (Exception e) {
					// TODO: handle exception
				}
				
				
			}
		}
		
		
		
		return true;
	}

}
